package com.fdb.efp.nls.service.impl.sx;

import static  com.fdb.basic.sequence.service.DefaultPatternDescriptor.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Objects;


import com.fdb.efp.nls.service.facade.NlsApplyRelationService;
import com.fdb.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.fdb.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.fdb.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.gdrcu.efp.cus.common.CusBankRelEnum;
import com.gdrcu.efp.cus.common.CusStatusEnum;
import com.gdrcu.efp.cus.common.CusTypeEnum;
import com.fdb.basic.sequence.service.DefaultPatternDescriptor;
import com.fdb.basic.sequence.service.PatternDescriptor;
import com.fdb.efp.nls.service.facade.PrdInfoService;
import com.fdb.efp.nls.service.vo.PrdInfoVO;
import com.fdb.efp.cus.service.facade.CusIndivRelService;
import com.fdb.efp.cus.service.facade.CusIndivService;
import com.fdb.efp.cus.service.vo.CusIndivVO;
import com.fdb.efp.esb.common.constant.ESBClientConstance;
import com.fdb.efp.esb.common.constant.MsLoanConstant;
import com.fdb.efp.esb.service.bo.req.hj.ReqCusInfoCreBean;
import com.fdb.efp.esb.service.bo.resp.hj.RespCusInfoCreBean;
import com.fdb.efp.esb.service.facade.hj.CustomerInfoCreateService;
import com.fdb.basic.framework.core.constant.SDicToExternalConstant;
import com.fdb.basic.framework.core.exception.BizException;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.ValidationUtils;
import com.fdb.basic.framework.core.util.sdic.SDicToExternal;
import com.fdb.efp.rule.common.enumeration.RefuseType;

/**
 * 客户建档节点
  * @author heyingfeng
  * @since 2019年3月6日 上午11:51:58
  * @version 1.0
 */
@Service("creditCusCreateService")
public class CreditCusCreateServiceImpl extends CreditSoltServiceImpl {

	private static final Logger log = LoggerFactory.getLogger(CreditCusCreateServiceImpl.class);
	private static final DateTimeFormatter timeStrFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	public static final PatternDescriptor PATTERN = 
			DefaultPatternDescriptor.of("CREL" + YEAR_4 + MONTH + DAY + SEQ, 8);
	private static final String other = "Other";
	@Override
	public void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsCreditInfoVO nlsCreditInfoVO) throws Exception {
		String applySeq = nlsProcessBizVo.getApplySeq();
		try {
			log.info("开始进行客户建档插槽,流水号:" + applySeq);
			Objects.requireNonNull(nlsCreditInfoVO);

			/** 去互金开户， 如果网贷存在该客户信息则不开户 **/
			String cusId = cusIndivService.getCusIdByCertCode(nlsCreditInfoVO.getCertType(), nlsCreditInfoVO.getCertCode());
			// 更新客户信息-客户编号赋值互金客户建档返回的用户号
			String usrID = "";
			boolean cusIndivExsit = true;
			try {
				if (cusId == null) {
					log.info("网贷不存在该客户，前往互金建档");
					ReqCusInfoCreBean reqCusInfoCreBean = new ReqCusInfoCreBean();
//					final ReqCusInfoCrePswdInfArry reqCusInfoCrePswdInfArry = new ReqCusInfoCrePswdInfArry();
//					reqCusInfoCrePswdInfArry.setPswdTp("WD");//密码类型
//					reqCusInfoCrePswdInfArry.setPyPswd("123456");//支付密码
//					// 密码信息数组
//					reqCusInfoCreBean.setPswdInfArry(reqCusInfoCrePswdInfArry);
					// 客户姓名
					reqCusInfoCreBean.setCustNm(nlsCreditInfoVO.getCusName());
					// 证件类型 
					reqCusInfoCreBean.setCertTp(nlsCreditInfoVO.getCertType());
					// 证件号码 
					reqCusInfoCreBean.setCertNo(nlsCreditInfoVO.getCertCode());
					// 签发机关（默认中国） 
					reqCusInfoCreBean.setIssueOrgNm("中国");
					// 手机号码 
					reqCusInfoCreBean.setMblNo(nlsCreditInfoVO.getIndivMobile());
					// 联系地址
					reqCusInfoCreBean.setCtcAddr(StringUtil.replaceNullByObj(nlsCreditInfoVO.getIndivRsdAddr()));
					// 民族
					reqCusInfoCreBean.setEthnic(StringUtil.replaceNullByObj(nlsCreditInfoVO.getEthnic()));
					// 客户英文名称
					reqCusInfoCreBean.setClntEnNm("");
					// 发证机关地区码
					reqCusInfoCreBean.setIssueOrgAddrCd("");
					// 最高学历
					reqCusInfoCreBean.setHighEdu(StringUtil.replaceNullByObj(nlsCreditInfoVO.getEdu()));
					// 国籍
					reqCusInfoCreBean.setNation("");
					// 职业
					reqCusInfoCreBean.setCrrCd(StringUtil.replaceNullByObj(nlsCreditInfoVO.getProfession()));
					// 职称
					reqCusInfoCreBean.setTtl(StringUtil.replaceNullByObj(nlsCreditInfoVO.getTtl()));
					// 出生日期
					reqCusInfoCreBean.setBrthDt("");
					// 工作单位名称
					reqCusInfoCreBean.setWrkCorpNm(StringUtil.replaceNullByObj(nlsCreditInfoVO.getWrkCorpNm()));
					// 工作单位地址
					reqCusInfoCreBean.setWrkCorpAddr(StringUtil.replaceNullByObj(nlsCreditInfoVO.getWrkCorpAddr()));
					// 工作单位电话
					reqCusInfoCreBean.setWrkCorpTel("");
					// 家庭地址
					reqCusInfoCreBean.setFamAddr("");
					// 家庭电话
					reqCusInfoCreBean.setFamTelNo("");
					// 个人月收入
					reqCusInfoCreBean.setIndvIncmAmt("");
					// 家庭月收入
					reqCusInfoCreBean.setFamIncmAmt("");
					// 婚姻状况
					reqCusInfoCreBean.setMrgSitu(StringUtil.replaceNullByObj(nlsCreditInfoVO.getMrgSitu()));
					// 配偶姓名
					reqCusInfoCreBean.setSpsNm(StringUtil.replaceNullByObj(nlsCreditInfoVO.getSpsNm()));
					// 户籍地址
					reqCusInfoCreBean.setDomcAddr(StringUtil.replaceNullByObj(nlsCreditInfoVO.getCertAddr()));
					// 配偶联系电话
					reqCusInfoCreBean.setSpsCtcTelNo("");
					// 配偶移动电话
					reqCusInfoCreBean.setSpsMblTelNo("");
					// 配偶客户号
					reqCusInfoCreBean.setSpsCustNo("");
					// 邮编
					reqCusInfoCreBean.setPstcd("");
					// 单位性质
					reqCusInfoCreBean.setCorpChar("");
					// 是否农户
					reqCusInfoCreBean.setWhthrFrmr("");
					// 用户性别
					reqCusInfoCreBean.setUserGnd(nlsCreditInfoVO.getGender());
					//cusId = "5000000066";
					//挡板 TODO
					reqCusInfoCreBean.setInstId(ESBClientConstance.bdInstId);
					// 产品类型  【需求变更】 @date 2019/06/27
					reqCusInfoCreBean.setProdType(SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_IFP, SDicToExternalConstant.PRD_TYPE, nlsCreditInfoVO.getPrdId()));
					RespCusInfoCreBean respCusInfoCreBean = customerInfoCreateService.customerInfoCreate(reqCusInfoCreBean);
					cusId = respCusInfoCreBean.getClntNo();
					// 互金客户建档-用户号
					usrID = respCusInfoCreBean.getUsrID();
					cusIndivExsit = false;
				} else {
					log.info("网贷已存在该客户，客户号：" + cusId);
				}
			} catch (Exception e) {
				log.error("调用互金核心客户建档异常", e);
				nlsProcessBizVo.setRefuseMsg(RefuseType.OTHER.getMsg());
				throw new BizException("调用互金核心客户建档异常", e);
			}
			String prdId = Objects.requireNonNull(nlsCreditInfoVO.getPrdId());
			PrdInfoVO prdInfoVo = new PrdInfoVO();
			prdInfoVo.setPrdId(prdId);
			prdInfoVo = prdInfoService.queryByPk(prdInfoVo);

			final String dateString = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
			final String dateTimeString = LocalDateTime.now().format(timeStrFormatter);
			final String createUser = "admin";

			/** 新增客户信息(如果不存在该客户信息) **/
			final CusIndivVO cusIndivVO = new CusIndivVO();
			cusIndivVO.setCusId(usrID);
			cusIndivVO.setInnerCusId(cusId);
			cusIndivVO.setCusName(nlsCreditInfoVO.getCusName());
			cusIndivVO.setIndivSex(ValidationUtils.getSexFromIdNumber(nlsCreditInfoVO.getCertCode()).getEnname());
			cusIndivVO.setCertType(nlsCreditInfoVO.getCertType());
			cusIndivVO.setCertCode(nlsCreditInfoVO.getCertCode());
			cusIndivVO.setPhone(nlsCreditInfoVO.getIndivMobile());
			cusIndivVO.setCusType(CusTypeEnum.NATURAL_MAN.getCode());
			cusIndivVO.setCusBankRel(CusBankRelEnum.NORMAL.getCode());
			cusIndivVO.setIndivHouhRegAdd(nlsCreditInfoVO.getCertAddr());
			cusIndivVO.setCusStatus(CusStatusEnum.OFFICIAL.getCode());
			// 民族
			cusIndivVO.setIndivNtn(nlsCreditInfoVO.getEthnic());
			// 学历
			cusIndivVO.setIndivEdt(nlsCreditInfoVO.getEdu());
			// 工作单位名称
			cusIndivVO.setIndivComName(nlsCreditInfoVO.getWrkCorpNm());
			// 工作单位地址
			cusIndivVO.setIndivComAddr(nlsCreditInfoVO.getWrkCorpAddr());
			// 配偶姓名
			cusIndivVO.setIndivSpsName(nlsCreditInfoVO.getSpsNm());
			// 职称
			cusIndivVO.setIndivCrtfctn(nlsCreditInfoVO.getTtl());
			// 职业
			cusIndivVO.setIndivOcc(nlsCreditInfoVO.getProfession());
			// 户籍地址
			cusIndivVO.setIndivHouhRegAdd(nlsCreditInfoVO.getCertAddr());
			// 居住地址
			cusIndivVO.setIndivRsdAddr(nlsCreditInfoVO.getIndivRsdAddr());

			// 首次申请渠道
			cusIndivVO.setFstAppChannel(prdInfoVo.getPrdType());
			// 婚姻状况
			cusIndivVO.setIndivMarSt(nlsCreditInfoVO.getMrgSitu());
			cusIndivVO.setInputId(createUser);
			cusIndivVO.setLastUpdateTime(dateTimeString);
			cusIndivVO.setLastUpdateUser(createUser);

			if (cusIndivExsit) {
				int num1 = cusIndivService.updateByPk(cusIndivVO);
				if (num1 == -1) {
					throw new BizException("客户数据表更新异常!");
				}
			} else {
				cusIndivVO.setComInitLoanDate(dateString);
				cusIndivVO.setInputDate(dateString);
				cusIndivVO.setCreateTime(dateTimeString);
				int num2 = cusIndivService.insertCusIndiv(cusIndivVO);

				if (num2 == -1) {
					throw new BizException("客户数据表增加异常!");
				}
			}
			/** 更新授信申请表 */
			if (!Objects.equals(nlsCreditInfoVO.getCusId(), usrID)) {
				nlsCreditInfoVO.setCusId(usrID);
				nlsCreditInfoService.updateByPk(nlsCreditInfoVO);
			}
		} catch (Exception e) {
			log.error(Arrays.toString(e.getStackTrace()));
			/**设置百度原因说明**/
			nlsCreditInfoVO.setBdReasonCode(MsLoanConstant.ReasonCodeMap.get(other));
			nlsCreditInfoVO.setBdReasonMsg(MsLoanConstant.ReasonMsgMap.get(other));
			nlsProcessBizVo.setExceptionFlag(true);
			nlsProcessBizVo.setExceptionMsg(e);
		}
	}

	@Autowired
	@Qualifier("nlsCreditInfoService")
	private NlsCreditInfoService nlsCreditInfoService;
	@Autowired
	@Qualifier("nlsApplyRelationService")
	private NlsApplyRelationService nlsApplyRelationService;
	@Autowired
	@Qualifier("customerInfoCreateService")
	private CustomerInfoCreateService customerInfoCreateService;
	@Autowired
	@Qualifier("prdInfoService")
	private PrdInfoService prdInfoService;
	@Autowired
	@Qualifier("cusIndivService")
	private CusIndivService cusIndivService;
	@Autowired
	@Qualifier("cusIndivRelService")
	private CusIndivRelService cusIndivRelService;
}
